package imserver.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;

import imserver.beans.FriendInfo;
import imserver.beans.MemberInfo;
import imserver.common.util.DaoException;
import imserver.dao.BaseDaoImpl;
import imserver.service.FriendService;
import imserver.service.MemberService;

public class FriendServiceImpl extends BaseDaoImpl<FriendInfo> implements FriendService{

	@Resource
	private MemberService memberService;
	
	@Override
	public void add(int ownerId, String memberNum) throws DaoException {
		Session session = getSession();
		Query query = session.createQuery("from friendInfo where owerId=:owerId");
		query.setParameter("owerId", ownerId);
		FriendInfo friendInfo = (FriendInfo)query.uniqueResult();
		MemberInfo memberInfo = memberService.getMember(memberNum);
		if( friendInfo == null){
			friendInfo = new FriendInfo();
			friendInfo.setOwerId(ownerId);
			List<MemberInfo> members = new ArrayList<MemberInfo>();
			members.add(memberInfo);
			friendInfo.setMembers(members);
			save(friendInfo);
		}else{
			List<MemberInfo> members = friendInfo.getMembers();
			members.add(memberInfo);
			friendInfo.setMembers(members);
			update(friendInfo);
		}
	}

	@Override
	public void del(int ownerId, int memberId) throws DaoException {
		Session session = getSession();
		Query query = session.createQuery("from friendInfo where owerId=:owerId");
		query.setParameter("owerId", ownerId);
		FriendInfo friendInfo = (FriendInfo)query.uniqueResult();
		if(friendInfo != null){
			for(int i=0; i< friendInfo.getMembers().size(); i++){
				friendInfo.getMembers().remove(i);
			}
			update(friendInfo);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MemberInfo> list(int id) throws DaoException {
		Session session = getSession();
		Query query = session.createQuery("from friendInfo where owerId=:owerId");
		query.setParameter("owerId", id);
		return query.list();
	}

}
